<?php
namespace Admin\Controller;
use Think\Controller;
use Org\Util\Authentication;
use \Org\Util\QRcode;
class ChannelController extends Controller {
	/**
	 * 渠道管理页数据
	 */
	public function index()
    {
		$this->Islogin();
		$channel_db = D('Channel');
		$admin_db = M('admin');
		$userid = session('lampzuo_id');
		$auth = $admin_db ->where('id='.$userid)->field('position')->find();
        // 激活总数
		$channel_data['jihuoliang'] = $channel_db->OneRelationCount(false,'jihuoliang');
        // 总数
		$channel_data['qudaozongl'] = $channel_db->OneRelationCount(false,'qudaozongl');
        // 待审核总数
		$channel_data['daishen'] = $channel_db->OneRelationCount(false,'daishen');
		echo json_encode([
            'success'=>'OK',
            // 数据
            'data'=>$channel_data,
            // 权限
            'auth'=>$auth['position'],
            // 域名
            'weburl'=>C('WEBURL'),
        ]);
	}

	/**
	 * 渠道驳回
	 */
	public function ChannelReject() 
    {
		$this->Islogin();
		$data    = I("post.");
		$wayuser = M('wayuser');
		$channel_db = D('Channel');
		$meid = session('lampzuo_id');
		$res = $wayuser->where(array('id'=>$data['id']))->find();
		if(!$res){
			echo "2";die;
		}
		if(empty($data['remark'])){
			$data['remark'] = '未填写原因';
		}
		$adddata = array(
			"status"=>$data['status'],
			"remark"=>$data['remark'],
			"verificationID"=>0,
			"distinguishRemarks"=>"",
			);
		$adddata['activation_time'] = time();
		$adddata['auditorfk'] = $meid;
		$resdata = $wayuser->where(array('id'=>$data['id']))->save($adddata);
		if($resdata&&$channel_db->record($data['id'],$data['status'],'被驳回原因：'.$data['remark'])){
			$this->ajaxReturn(array('ret'=>$resdata));
		}else{
			$this->ajaxReturn(array('error'=>'1','message'=>'抱歉！数据添加失败，请稍后再试。'));
		}
	}
	
	/**
	 * 返回渠道修改数据和 查看驳回原因
	 */
	public function getReject() { 
		// $this->Islogin();
		$wayuser = M("wayuser");
		$open    = M("wayuser_operation");
		$data    = I("post.");
		if($data['sta'] == 2 || $data['sta'] == 1){
			$res = $open->where(array('wayuserid'=>$data['id'],'status'=>$data['status']))->order("id desc")->find();
			$res['sta'] = $data['sta'];
		}else{
			$res = $wayuser->where(array('id'=>$data['id']))->find();
            // print_r($res);die;
			$res['receiptcode']     = serializeMysql($res['receiptcode'],1);
	    	$res['doorhead']        = serializeMysql($res['doorhead'],1);
            $res['roomscene']       = serializeMysql($res['roomscene'],1);
            $res['otherdata_url']   = serializeMysql($res['otherdata_url'],1);
	    	$res['poster']          = serializeMysql($res['poster'],1);
		}
		if(!$res){
			echo "-1";die;
		}		
		$this->ajaxReturn(array("data"=>$res,'weburl'=>C('OSSURL')));
	}
	
	/**
	 * 修改渠道信息
	 */
	public function editChannel(){
		$this->Islogin();
		$data  = I("post.");
		$ches  = D("Channel");
		$receiptcode= array_filter($data['receiptcode']);
		$doorhead   = array_filter($data['doorhead']);
        $roomscene  = array_filter($data['roomscene']);
        $poster     = array_filter($data['poster']);
        $qita       = array_filter($data['qita']);
		$addres = $this->isFuncgetImgesQudao($_FILES);
        if(count($receiptcode)>0 && count($addres['receiptcode'])>0){
           $data['receiptcode'] = array_merge($receiptcode,$addres['receiptcode']);
        }else{
           $data['receiptcode'] = count($receiptcode)>0?$receiptcode:$addres['receiptcode'];
        }
		if(count($doorhead)>0 && count($addres['doorhead'])>0){
           $data['doorhead'] = array_merge($doorhead,$addres['doorhead']);
        }else{
           $data['doorhead'] = count($doorhead)>0?$doorhead:$addres['doorhead'];
        }
        if(count($roomscene)>0 && count($addres['roomscene'])>0){
           $data['roomscene'] = array_merge($roomscene,$addres['roomscene']);
        }else{
           $data['roomscene'] = count($roomscene)>0?$roomscene:$addres['roomscene'];
        }
        if(count($poster)>0 && count($addres['poster'])>0){
           $data['poster'] = array_merge($poster,$addres['poster']);
        }else{
           $data['poster'] = count($poster)>0?$poster:$addres['poster'];
        }
        if(count($qita)>0 && count($addres['qita'])>0){
           $data['qita'] = array_merge($qita,$addres['qita']);
        }else{
           $data['qita'] = count($qita)>0?$qita:$addres['qita'];
        }
        // // 排除已存在的身份证
        // if($data['id']){
        //     $identify_is = $ches->OnefieldData(['identify'=>$data['identify']],['identify'],['status'=>['<>','-1'],'id'=>['<>',$data['id']]]);
        //     if($identify_is){
        //         $this->ajaxReturn(array('error'=>'ERROR','message'=>'抱歉！要修改的身份证已存在!'));
        //     }
        // }else{
        //     $this->ajaxReturn(array('error'=>'ERROR','message'=>'抱歉！数据修改失败，请稍后再试。'));
        // }
        //$path = C('PUBLIC_ROUTE').'/Public/Uploads/identify/';
        //$identify_img = [$data['identity_A'],$data['identity_B'],$data['people_H']];
		// $data['identify_url'] = '';
		// for ($i=0; $i < 3; $i++) { 
		// 	$data['identify_url'] .= $identify_img[$i].',';
		// }
		// $data['identify_url'] = trim($data['identify_url'],',');
        $res = $ches->isEditQuDao($data);
        return  $this->ajaxReturn($res);
	}

	/**
     * 渠道风控审核列表
     */
    public function ChannelListIndex() {
    	$this->Islogin();
        // 判断是否是ajax请求
    	if(!empty(I('post.getall'))&&I('post.getall')=='aj'){
    		$channel_db = D('channel');
            // 获取渠道列表json格式
        	$channel_data = $channel_db->ListAllChannel(false,true);
        	echo json_encode($channel_data['data']);return;
    	}else{
    		$channel_db = D('channel');
            // 获取渠道列表
	        $channel_data = $channel_db->ListAllChannel();
	        $page = $channel_data['page'];
	        $show = $page->show();
	        $this->assign('channel_data',$channel_data['data']);
	        $this->assign('page_show',$show);
	        $this->assign('page',$page);
	        $this->display('channellist');
    	}
    }

    /**
     * 获取所有的渠道数据
     */
    public function ChannelCountAll() {
    	echo M('wayuser')->where('status=1')->count();
    }

    /**
     * 按条件统计所有渠道
     */
    public function ChannelCount() {
    	$meid = $this->Islogin();
    	$channel_db =  M('wayuser');
    	$admin_db =  M('admin');
    	$user_db =  M('user');
    	$order_db = M('order');
    	$device_db = M('device');
    	$city_db =  D('city');
    	$admin_data = $admin_db->where('id='.$meid)->find();
    	$post = I('post.');
    	$count_data = [];
        // 各个权限的条件区分
    	switch($admin_data['position']){
            // 全国权限
            case '1100':
                if ($post['provinceid'] != '0' && !empty($post['provinceid'])) {
                    $where_city = ' and provinceid=' . $post['provinceid'];
                } else {
                    $where_city = '';
                }
                // 用户总数
                $count_data['user_count'] = $user_db->count();
                // 已用户总数
                $count_data['user_count_ac'] = $user_db->where('last_login_time<>0')->count();
                // 未登录用户总数
                $count_data['user_count_login'] = $count_data['user_count'] - $count_data['user_count_ac'];
                $response['provinceid'] = $city_db->CityGetAll(false, false, false);

                //APP总注册量
                $count_data['register_total'] = $user_db -> count();
                //APP总安装量
                $install_total = $device_db -> count();
                $count_data['install_total'] = $install_total >= $count_data['register_total'] ? $install_total : $count_data['register_total'];
                //渠道总量
                $count_data['channel_total'] = $channel_db -> count();
                //渠道客户总注册量
                $channel_register = $user_db -> where('waynum > 0') -> count();
                $count_data['channel_register'] = $channel_register;
                //渠道客户总访问量
                $channel_client = $channel_db -> where('countvisit > 0') -> select();
                $channel_client_count = 0;
                foreach ($channel_client as $k => $v) {
                    $channel_client_count += $channel_client[$k]['countvisit'];
                }
                $count_data['channel_client_count'] = $channel_client_count >= $channel_register ? $channel_client_count : $channel_register;
                //渠道注册转化率
                $count_data['channel_register_z'] = $channel_register / $count_data['channel_client_count'] * 100;
                //渠道客户总提单量
                $channel_order_total = $order_db -> join('jdc_user on jdc_order.uid=jdc_user.id') ->where('jdc_user.waynum > 0') -> count();
                $count_data['channel_order_total'] = $channel_order_total;
                //渠道提单量转化率
                $count_data['channel_order_z'] = $channel_order_total / $channel_register * 100;
                break;
            // 城市经理权限
            case '3':
                $where_city = ' and pid='.$admin_data['id'];
                break;
            // 省总权限
    		case '4':
    			$where_city = ' and provinceid='.$admin_data['provinceid'];
    		    break;
    		default:
    			echo json_encode(['error'=>'1','message'=>'您的账号权限不能查看该数据！']);
                return;
    	}
    	// 某省或全国的所有gw
    	$gw = $admin_db->where('position=1'.$where_city.$this->istest['testsql'])->field('id')->select();
        if($gw){
            // gw的ID拼接
            $gw_ids = implode(',',array_column($gw,'id'));
            // 拼接sql
            $gw_wherecity_ids = $where_city==''?'':' and admin_id in('.$gw_ids.')';
        }else{
            // 拼接sql
            $gw_wherecity_ids = $where_city==''?'':' and 1=2';
        }
    	
    	// 所有的Gw
    	$count_data['gwcount'] = count($gw);
    	// 全部的渠道总数
    	$count_data['channel_count'] = $channel_db->where("1=1".$gw_wherecity_ids)->count();
    	// 全部的待审核
    	$count_data['channel_count_examine'] = $channel_db->where('status=0'.$gw_wherecity_ids)->count();
    	// 全部的通过
    	$count_data['channel_count_success'] = $channel_db->where('status>=2'.$gw_wherecity_ids)->count();
    	// 全部的被拒绝
    	$count_data['channel_count_refuse'] = $channel_db->where('status=-1'.$gw_wherecity_ids)->count();
    	// 全部的驳回数量
    	$count_data['channel_count_back'] = $channel_db->where('status=-2'.$gw_wherecity_ids)->count();
    	$response['success'] = 'OK';
    	$response['data'] = $count_data;
    	$response['position'] = $admin_data['position'];
    	echo json_encode($response,true);
    	return;
    }

    

    /**
     * 下载二维码文件
     */
    public function DownloadScerweima() {
        $filename_str = I('get.filename');
        if(empty($filename_str)){
           return false;
        }
        $path = C('PUBLIC_ROUTE').'/Public/Uploads/qrcode/';
        $filename = $path.ltrim($filename_str,'/');
        header("Content-type: octet/stream");
        // 告诉浏览器通过附件形式来处理文件
        header( "Content-disposition:attachment;filename=".explode('/',$filename_str)[1]); 
        // 下载文件大小
        header('Content-Length:'.filesize($filename)); 
        // 读取文件内容
        readfile($filename);
    }

    /** 
     * GW的渠道列表
     */
    public function GwChannelList() {
    	$channel_db =  M('wayuser');
    	$channel_action_db =  M('wayuser_operation');
    	$admin_db =  M('admin');
    	$city_db =  D('city');
    	$Gwid = I('get.gwid');
        // 筛选时间段
        // 本月开始的时间戳
        $BeginDate = strtotime(date("Y-m-01"));
        // 本月结束的时间戳
        $EndDate = mktime(0, 0, 0,date('m')+1,1)-1;
        // 今日开始的时间戳
        $Beginday = strtotime(date('Y-m-d 00:00:00'));
        // 今日结束的时间戳
        $EndDay = strtotime(date('Y-m-d 23:59:59'));
        // $timesql = ' and create_time>='.$Beginday.' and create_time<='.$EndDay;
        $timesql = '';
        // 查询满足要求的总记录数
        $count= $channel_db->where('admin_id='.$Gwid.$timesql)->count();
        $tiao = 8;
        // 实例化分页类 传入总记录数和每页显示的记录数($tiao)
        $Page = new \Think\Page($count,$tiao);
        $currentpage = empty(I('get.p'))?1:I('get.p');
        // 获取当前页的数据
    	$channel_data_my = $channel_db->where('admin_id='.$Gwid.$timesql)->limit($Page->firstRow.','.$Page->listRows)->field('id,name,tel,company,waynum,status')->ORDER('status desc')->select();
        if(!$channel_data_my){
            exit(json_encode(['error'=>'1','message'=>'没有更多数据了！']));
        }
        // 渠道状态
    	$status_arr = ['0'=>'等待城市经理审核','1'=>'等待风控审核','2'=>'已激活','3'=>'关闭状态（已通过审核）','-1'=>'被拒绝','-2'=>'被驳回（正在修改）'];
    	foreach ($channel_data_my as $k => $v) {
    		$channel_data_my[$k]['status'] = $status_arr[$channel_data_my[$k]['status']];
    	}
        exit(json_encode(['success'=>'OK','data'=>$channel_data_my,'p'=>$currentpage,'pagecount'=>ceil($count/$tiao)]));
    }

    /**
     * 按条件统计今日渠道
     */ 
    public function dayCountChannel() {
    	$meid = $this->Islogin();
    	$channel_db =  M('wayuser');
    	$channel_action_db =  M('wayuser_operation');
    	$admin_db =  M('admin');
    	$user_db =  M('user');
    	$city_db =  D('city');
    	$admin_data = $admin_db->where('id='.$meid)->find();
    	$post = I('post.');
    	$count_data = [];
        // 今天的00点
    	$day = date('Y-m-d 00:00:00');
        // 今天的00点时间戳
    	$day_time = strtotime($day);
        // 今天的最后一刻
    	$day_end = date('Y-m-d 23:59:59');
        // 今天的最后一刻的时间戳
    	$day_end_time = strtotime($day_end);
    	switch($admin_data['position']){
    		case '1100':
    		    if($post['provinceid']!='0'&&!empty($post['provinceid'])){
    		    	$where_city = ' and provinceid='.$post['provinceid'];
    		    }else{
    		    	$where_city = '';
    		    }
    			// 今日注册用户
    			$count_data['user_count'] = $user_db->where('create_time >= '.$day_time.' and create_time<='.$day_end_time)->count();
		    	// 今日登录用户
		    	$count_data['user_count_ac'] = $user_db->where('last_login_time>='.$day_time.' and last_login_time<='.$day_end_time)->count();
		    	$response['provinceid'] = $city_db->CityGetAll(false,false,false);
    		    break;
            case '3':
                $where_city = ' and pid='.$admin_data['id'];
                break;
    		case '4':
    			$where_city = ' and provinceid='.$admin_data['provinceid'];
    		    break;
    		default:
    			echo json_encode(['error'=>'1','message'=>'您的账号权限不能查看该数据！']);return;
    	}
    	// 某省或全国的所有gw
    	$gw = $admin_db->where('position=1'.$where_city.$this->istest['testsql'])->field('id')->select();
        if($gw){
            // gw的ID拼接
            $gw_ids = implode(',',array_column($gw,'id'));
            // 拼接sql
            $gw_wherecity_ids = $where_city==''?'':' and admin_id in('.$gw_ids.')';
        }else{
            // 拼接sql
            $gw_wherecity_ids = $where_city==''?'':' and 1=2';
        }
    	if($where_city==''){
    		$channel_sql = '';
    	}else{
    		// 某省或全国的所有渠道
	    	$channel = $channel_db->where('admin_id in('.$gw_ids.')')->field('id,waynum,admin_id')->select();
	    	if($channel){
	    		// 可统计渠道的ID拼接
	    		$channel_ids = implode(',',array_column($channel,'id'));
	    	}else{
	    		$channel_ids = '0';
	    	}
	    	$channel_sql = ' and wayuserid in('.$channel_ids.')';
    	}
    	// 今日新增GW
    	$count_data['gwcount'] = $admin_db->where('position=1 and insert_time>='.$day_time.' and insert_time<='.$day_end_time.$where_city.$this->istest['testsql'])->count();
    	// 全部的渠道总数
    	$count_data['channel_count'] = $channel_db->where("create_time>=".$day_time.' and create_time<='.$day_end_time.$gw_wherecity_ids)->count();
    	// 全部的通过
    	$count_data['channel_count_success'] = $channel_action_db->where('status=2 and create_time>='.$day_time.' and create_time<='.$day_end_time.$channel_sql)->count();
    	// 全部的被拒绝
    	$count_data['channel_count_refuse'] = $channel_action_db->where('status=-1 and create_time>='.$day_time.' and create_time<='.$day_end_time.$channel_sql)->count();
    	// 全部的驳回数量
    	$count_data['channel_count_back'] = $channel_action_db->where('status=-2 and create_time>='.$day_time.' and create_time<='.$day_end_time.$channel_sql)->count();
    	
    	$response['success'] = 'OK';
    	$response['data'] = $count_data;
    	$response['position'] = $admin_data['position'];
    	echo json_encode($response,true);
    	return;
    }

    /**
     * 所有风控已操作的渠道
     */
    public function ChannelFkAction() {
    	$this->Islogin();
    	$channel_db = D('channel');
        // 获取已操作列表数据
        $channel_data = $channel_db->FkAction([
            'jdc_admin.name',
            'jdc_admin.usernum',
            'jdc_wayuser.status',
            'jdc_wayuser.activation_time',
            'jdc_wayuser.auditorfk',
            'jdc_wayuser.waynum',
            'jdc_wayuser.admin_id',
            'jdc_wayuser.create_time',
            'jdc_wayuser.name',
            'jdc_wayuser.id',
        ]);
        $page = $channel_data['page'];
        $show = $page->show();
        $this->assign('channel_data',$channel_data['data']);
        $this->assign('page_show',$show);
        $this->assign('page',$page);
        $this->display('channellistfk');
    }

    /**
     * 渠道风控审核详细
     */
    public function ChannelDetailskf() {
    	$this->Islogin();
    	$id = $_GET['id'];
    	$channel_db = D('Channel');
    	$channel_data = $channel_db->ChannelDetailsInfo($id);
    	$channel_data['receiptcode1']     = serializeMysql($channel_data['receiptcode'],1);
    	$channel_data['doorhead1']      = serializeMysql($channel_data['doorhead'],1);
        $channel_data['roomscene1']     = serializeMysql($channel_data['roomscene'],1);
    	$channel_data['poster1']    = serializeMysql($channel_data['poster'],1);
        $channel_data['receiptcode'] = [];
        $channel_data['doorhead'] = [];
        $channel_data['roomscene'] = [];
        $channel_data['poster'] = [];
        foreach ($channel_data['receiptcode1']  as $key => $value) {
            $channel_data['receiptcode'][] = substr($value, 1);
        }
        foreach ($channel_data['doorhead1']  as $key => $value) {
            $channel_data['doorhead'][] = substr($value, 1);
        }
        foreach ($channel_data['poster1']  as $key => $value) {
            $channel_data['poster'][] = substr($value, 1);
        }
        foreach ($channel_data['roomscene1']  as $key => $value) {
            $channel_data['roomscene'][] = substr($value, 1);
        }

    	if($channel_data['channeltype'] == 1){
        	$channel_data['channeltype'] = "外部渠道";
    	}else if($channel_data['channeltype'] == 2){
    		$channel_data['channeltype'] = "内部渠道";
    	}
        if($channel_data['scenetype'] == 1){
            $channel_data['scenetype'] = "个人渠道";
        }else if($channel_data['scenetype'] == 2){
            $channel_data['scenetype'] = "场景渠道";
        }
        if($channel_data['identify_url']){
            $channel_data['identify_url'] = explode(',', $channel_data['identify_url']);
            $channel_data['addtype_url'] = '1';
        }
        $channel_data['ossurl'] = C('OSSURL');
    	// $channel_data['identify_url'] = explode(',', $channel_data['identify_url']);
    	$this->assign('channel_data',$channel_data);
    	$this->assign('receiptcodeurl',count($channel_data['receiptcode']));
    	$this->assign('doorheadurl',count($channel_data['doorhead']));
        $this->assign('roomscenerurl',count($channel_data['roomscene']));
    	$this->assign('posterrurl',count($channel_data['poster']));
    	$this->display('channeldetails');
    }

	/**
	 * 执行渠道信息保存操作
	 */
	public function ActionChannel() {
		$this->Islogin();
		$cannel_DB = D('Channel');
		$data = I('post.');
		if($_FILES){
			$addres = $this->getImgesQudao($_FILES);
			$data["receiptcode"] = $addres['receiptcode'];
            $data["doorhead"] = $addres['doorhead'];
            $data["roomscene"] = $addres['roomscene'];
            $data["poster"] = $addres['poster'];
		}
        // $data['age'] = getAgeByID($data['identify']);
		$user_db = M('admin');
        $userid = session('lampzuo_id');
        $identifyisok = session('identifyisOK');
        // 当前用户的数据
		$user_data = $user_db->where('id='.$userid)->find();
		$auth = ['1','3'];
        // 验证当前用户的操作权限
        if(!in_array($user_data['position'],$auth)){
        	echo json_encode(['error'=>'3','message'=>'对不起，您的账号权限无法完成此操作！']);return;
        }
        // 通过手机号查询渠道
		$phone = $cannel_DB->OnefieldData(['tel'=>trim($data['phone'])],['tel'],['status'=>['<>','-1']]);
		if($phone){
			echo json_encode(['error'=>'4','message'=>'手机号已经存在，请确认！']);return;
		}
        // // 通过手机号查询渠道
        // $identify = $cannel_DB->OnefieldData(['identify'=>trim($data['identify'])],['identify'],['status'=>['<>','-1']]);
        // if($identify){
        //     echo json_encode(['error'=>'4','message'=>'身份证号已经存在，请确认！']);return;
        // }
        
        // 执行写入操作
        $res = $cannel_DB->ActionChannel($data);
       
        if($res){
        	session('identifyisOK',null);
        	echo json_encode(['success'=>'OK','message'=>'渠道信息已保存！','id'=>$res],true);
        	return;
        }else{
        	echo json_encode(['error'=>'2','message'=>'数据添加失败，请稍后重试！'],true);
        	return;
        }
	}
	/**
	 * 图片处理
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function getImgesQudao($data){

		$receiptcode = array();
        $doorhead    = array();
        $roomscene   = array();
		$poster      = array();
        // $data["receiptcode"] = $addres['receiptcode'];
        // $data["doorhead"] = $addres['doorhead'];
        // $data["roomscene"] = $addres['roomscene'];
        // $data["poster"] = $addres['poster'];
		$config = C('DOWNLOAD_UPLOAD');
		$config['rootPath'] =  './Public/Uploads/';
		if(!is_dir($config['rootPath'])){
            chmod($config['rootPath'],0777);
        }
		if($data['receiptcode']){
			$config['subName']  = "receiptcode";
            $datepath = 'Public/Uploads/receiptcode';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
			$upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['receiptcode']['name'] as $key=>$value){
                $type     = $value;//文件名
                $type1    = getImagetype($type);
                if(!$type1){
                    echo json_encode(['error'=>'3','message'=>'营业执照请上传图片格式！']);die;
                }
                $file1=array();
                $file1["receiptcode"]['name']=$value;
                $file1["receiptcode"]['type']=$data['receiptcode']["type"][$key];
                $file1["receiptcode"]['tmp_name']=$data['receiptcode']["tmp_name"][$key];
                $file1["receiptcode"]['error']=$data['receiptcode']["error"][$key];
                $file1["receiptcode"]['size']=$data['receiptcode']["size"][$key];
                $info    =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['receiptcode']['savepath'].$info['receiptcode']['savename']);
                array_push($receiptcode,$config['rootPath'].$info['receiptcode']['savepath'].$info['receiptcode']['savename']);
            }
		}
		if($data['doorhead']){
			$config['subName']  = "doorhead";
            $datepath = 'Public/Uploads/doorhead';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
			$upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['doorhead']['name'] as $key=>$value){
                $type     = $value;//文件名
                $type1    = getImagetype($type);
                if(!$type1){
                    echo json_encode(['error'=>'3','message'=>'授权证明请上传图片格式！']);die;
                }
                $file1=array();
                $file1["doorhead"]['name']=$value;
                $file1["doorhead"]['type']=$data['doorhead']["type"][$key];
                $file1["doorhead"]['tmp_name']=$data['doorhead']["tmp_name"][$key];
                $file1["doorhead"]['error']=$data['doorhead']["error"][$key];
                $file1["doorhead"]['size']=$data['doorhead']["size"][$key];
                $info   =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['doorhead']['savepath'].$info['doorhead']['savename']);
                array_push($doorhead,$config['rootPath'].$info['doorhead']['savepath'].$info['doorhead']['savename']);
            }
		}
        if($data['roomscene']){
            $config['subName']  = "roomscene";
            $datepath = 'Public/Uploads/roomscene';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
            $upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['roomscene']['name'] as $key=>$value){
                $type     = $value;//文件名
                $type1    = getImagetype($type);
                if(!$type1){
                    echo json_encode(['error'=>'3','message'=>'授权证明请上传图片格式！']);die;
                }
                $file1=array();
                $file1["roomscene"]['name']=$value;
                $file1["roomscene"]['type']=$data['roomscene']["type"][$key];
                $file1["roomscene"]['tmp_name']=$data['roomscene']["tmp_name"][$key];
                $file1["roomscene"]['error']=$data['roomscene']["error"][$key];
                $file1["roomscene"]['size']=$data['roomscene']["size"][$key];
                $info   =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['roomscene']['savepath'].$info['roomscene']['savename']);
                array_push($roomscene,$config['rootPath'].$info['roomscene']['savepath'].$info['roomscene']['savename']);
            }
        }
        if($data['poster']){
            $config['subName']  = "poster";
            $datepath = 'Public/Uploads/poster';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
            $upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['poster']['name'] as $key=>$value){
                $type     = $value;//文件名
                $type1    = getImagetype($type);
                if(!$type1){
                    echo json_encode(['error'=>'3','message'=>'授权证明请上传图片格式！']);die;
                }
                $file1=array();
                $file1["poster"]['name']=$value;
                $file1["poster"]['type']=$data['poster']["type"][$key];
                $file1["poster"]['tmp_name']=$data['poster']["tmp_name"][$key];
                $file1["poster"]['error']=$data['poster']["error"][$key];
                $file1["poster"]['size']=$data['poster']["size"][$key];
                $info   =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['poster']['savepath'].$info['poster']['savename']);
                array_push($poster,$config['rootPath'].$info['poster']['savepath'].$info['poster']['savename']);
            }
        }
        foreach ($receiptcode as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
        foreach ($doorhead as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
        foreach ($roomscene as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
        foreach ($poster as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
		$addarr= array(
                "receiptcode" => serializeMysql($receiptcode),
                "doorhead"    => serializeMysql($doorhead),
                "roomscene"   => serializeMysql($roomscene),
                "poster"      => serializeMysql($poster),
              );
		return  $addarr;
	}
	/**
	 * 渠道确认上传证件是否合格
	 */
	public function ConfirmIdentity() {
		$this->Islogin();
		$identity_info = I('post.');
		if(empty($identity_info['identity_A'])){
			echo json_encode(['error'=>'1','message'=>'请上传身份证正面照片！']);return;
		}

		if(empty($identity_info['identity_B'])){
			echo json_encode(['error'=>'1','message'=>'请上传身份证反面照片！']);return;
		}

		if(empty($identity_info['people_H'])){
			echo json_encode(['error'=>'1','message'=>'请上传个人上身照片！']);return;
		}
		
		$date = date('Ymd');
		$time = time();
        // 图片的存储位置
		$path = C('PUBLIC_ROUTE').'/Public/Uploads/identify/'.$date.'/';
		$randstr = randomkeys(5);
		// 转化base64格式为图片
		$identity_A_file = Base64DecodeImage($identity_info['identity_A'],$path,$randstr);
		if(!$identity_A_file){
			echo json_encode(['error'=>'2','message'=>'正面身份证照片上传失败！']);return;
		}
		$identity_B_file = Base64DecodeImage($identity_info['identity_B'],$path,$randstr);
		if(!$identity_B_file){
			echo json_encode(['error'=>'2','message'=>'正面身份证照片上传失败！']);return;
		}
		$people_H_file = Base64DecodeImage($identity_info['people_H'],$path,$randstr);
		if(!$people_H_file){
			echo json_encode(['error'=>'2','message'=>'正面身份证照片上传失败！']);return;
		}
		rotate($path.$identity_A_file,intval($identity_info['identity_Anum1']));
		rotate($path.$identity_B_file,intval($identity_info['identity_Bnum2']));
		rotate($path.$people_H_file,intval($identity_info['identity_Bnum3']));
		$srcimg['IdentityJust'] = $path.$identity_A_file;//身份证正面
	    $srcimg['IdentityBack'] = $path.$identity_B_file;//身份证反面
        $datepath = 'Public/Uploads/identify/'.$date;
        if(!ossGetObject($datepath))
        {
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            $res=createObjectDir($datepath);
        }
        ossPutObject($datepath.'/'.$identity_A_file,file_get_contents($path.$identity_A_file));
        ossPutObject($datepath.'/'.$identity_B_file,file_get_contents($path.$identity_B_file));
        ossPutObject($datepath.'/'.$people_H_file,file_get_contents($path.$people_H_file));
        // 示例化验证类
	    $auth = new Authentication();
        // 获取身份证信息
	    $res = $auth->IdentityAuth($srcimg);
        // 判断返回信息
	    if(isset($res['error'])&& $res['error']>0){
	    	session('identifyisOK',1);
	    	echo json_encode($res);
	    	return;

	    }else if($res['success']=='OK'){
            // 通过生日计算出当前年龄
	    	$nianling = function ($birthday) {
			 $age = strtotime($birthday); 
			 if($age === false){ 
			  return false; 
			 }
			 list($y1,$m1,$d1) = explode("-",date("Y-m-d",$age)); 
			 $now = strtotime("now"); 
			 list($y2,$m2,$d2) = explode("-",date("Y-m-d",$now));
			 $age = $y2 - $y1;
			 if((int)($m2.$d2) < (int)($m1.$d1)){
			 	$age -= 1;
			 }
			 return $age;
			};
            // 后续通过该值判断是否通过身份验证
	    	session('identifyisOK',6);
	    	$identifyinfo = $res['data']['IdentityJustInfo'];
	    	$cannel_DB = D('Channel');
            // 排除已存在的身份证
	    	if($identity_info['id']){
	    		$identify_is = $cannel_DB->OnefieldData(['identify'=>strtolower($identifyinfo['id_card_number'])],['identify'],['status'=>['<>','-1'],'id'=>['<>',$identity_info['id']]]);
	    	}else{
	    		$identify_is = $cannel_DB->OnefieldData(['identify'=>strtolower($identifyinfo['id_card_number'])],['identify'],['status'=>['<>','-1']]);
	    	}
            // 排除已存在的身份证
			if($identify_is){
				echo json_encode(['error'=>'4','message'=>'身份证号已经存在，请确认！']);die;
			}
            // 通过生日计算年龄
	    	$ident_birthday = $nianling($identifyinfo['birthday']['year'].'-'.$identifyinfo['birthday']['month'].'-'.$identifyinfo['birthday']['day']);
            // 响应客户端数据
	    	$this->ajaxReturn([
	    		'success'=>'OK',
                // 身份信息
	    		'data'=>array(
	    			'name'=>$identifyinfo['name'],
	    			'gender'=>$identifyinfo['gender'],
	    			'id_card_number'=>$identifyinfo['id_card_number'],
	    			'birthday'=>$identifyinfo['birthday'],
	    			'age'=>$ident_birthday,
	    			'address'=>$identifyinfo['address'],
	    			),
                // 身份证图片地址
	    		'identify_img'=>array(
	    			'A'=>$date.'/'.$identity_A_file,
	    			'B'=>$date.'/'.$identity_B_file,
	    			'H'=>$date.'/'.$people_H_file,
	    			),
	    		'message'=>'验证成功！',
	    		]);
	    }else{
	    	session('identifyisOK',1);

	    	echo json_encode(['error'=>'8','message'=>'系统出错，请联系系统管理员处理！']);die;
	    }
	}

	/**
	 * 风控确认上传证件是否合格
	 */
	public function ConfirmIdentityEdit() {
		$this->Islogin();
		$identity_info = I('post.');
		$wayuser_info = M('wayuser');
		if(empty($identity_info['identity_A'])){
			echo json_encode(['error'=>'1','message'=>'身份证正面照片未找到,请检查！']);return;
		}

		if(empty($identity_info['identity_B'])){
			echo json_encode(['error'=>'1','message'=>'身份证反面照片未找到,请检查！']);return;
		}

		if(empty($identity_info['people_H'])){
			echo json_encode(['error'=>'1','message'=>'个人上身照片未找到,请检查！']);return;
		}
		$path = C('PUBLIC_ROUTE').'/Public/Uploads/identify/';
        // 身份证正面
		$srcimg['IdentityJust'] = $path.$identity_info['identity_A'];
        // 身份人脸照片
        $srcimg['UserFaceJust'] = $path.$identity_info['people_H'];
	    $auth = new Authentication();
        // 运行检测接口
	    $res = $auth->IdentityAuthRisk($srcimg);
	    if(isset($res['error'])&& $res['error']>0){
	    	$dataType = array('verificationID'=>2,'distinguishRemarks'=>$res['message']);
	    	$wayuser_info->where(array('id'=>$identity_info['id']))->save($dataType);
	    	echo json_encode($res);
	    	return;
	    }else if($res['success']=='OK'){
	    	$dataType = array('verificationID'=>1);
	    	$wayuser_info->where(array('id'=>$identity_info['id']))->save($dataType);
	    	$identifyinfo = $res['data']['IdentityJustInfo'];
	    	echo json_encode(['success'=>'OK','data'=>['name'=>$identifyinfo['name'],'gender'=>$identifyinfo['gender'],'id_card_number'=>$identifyinfo['id_card_number'],'birthday'=>$identifyinfo['birthday'],'address'=>$identifyinfo['address']],'message'=>'经过与证件照对比,通过验证！']);
            @unlink($srcimg['UserFaceJust']);
            @unlink($srcimg['IdentityJust']);
            @unlink($path.$identity_info['identity_B']);
	    	return;

	    }else{
	    	exit(json_encode(['error'=>'8','message'=>'系统出错，请联系系统管理员处理！']));
	    }
	}

	/**
	 * 分批返回数据
	 */
	public function ResponseChannelList() {
		$this->Islogin();
		$channel_db = D('Channel');
		$admin_mdb = M('admin');
		$field = [
			'id',
			'waynum',
			'type',
			'name',
			'tel',
			'status',
			'qrcode_url',
			"remark",
			"scenetype",
		];
        //筛选
		$sx = I('get.sx');
		$arr_sx = [
        //待审核
		 '1'
        //激活
	    ,'2'
        //已关闭
	    ,'3'
		];
		if(in_array($sx,$arr_sx)){
			$wheresx = true;
		}
        //排序
		$order = I('get.order');
		$arr_order = [
         //激活时间
		 '1'
         //订单总
		,'2'
		];
		$arr_orderone = [
		'0'=>'create_time',
		'1'=>'activation_time',
		'2'=>'ordercount'
	    ];
		if(in_array($order,$arr_order)){
			$whereorder = true;
		}else{
			$order = 0;
		}
		$group_param = I('get.group');
        //A组 B组
		$group_arr = ['1','2'];
		$group = false;
		if(in_array($group_param,$group_arr)){
			$group = true;
		}
        //搜索
		$search = I('get.keys');
		// $limit = 10;
		// $page = I('get.page');
		// if($page>0) {
		// 	$limit2 = intval($page);
		// 	$lr = [intval($page)*$limit,$limit];
		// }else{
		// 	$lr = [0,$limit];
		// }
         
		$meid = session('lampzuo_id');
        $admin_data = $admin_mdb->where('id='.$meid)->find();
        if(!$admin_data){
            echo json_encode(['error'=>'2','message'=>'您没有权限查看！'],true);die;
        }
        // 销售顾问 '-1'被拒绝 '1-0'审核中 '1-1'审核中 '1-2'审核通过 '1-3'已关闭可开启 '-2'被驳回
        // 城市经理 '2--1'被拒绝 '2-0'审核 '2-1'审核中 '2-2'审核通过 '2-3'已关闭可开启 '2-4'被驳回
        // 省总 '3--1'被拒绝 '3-0'审核中 '3-1'审核中 '3-2'审核通过 '3-3'已关闭 '2-4'被驳回
        // 全国 '3--1'被拒绝 '3-0'审核中 '3-1'审核中 '3-2'审核通过 '3-3'已关闭 '2-4'被驳回
        switch ($admin_data['position']) {
            // 顾问权限
            case '1':
                $where = 'jdc_wayuser.admin_id='.$meid.' and jdc_wayuser.status>=-2';
                if($wheresx){
                    // 待审核
                	if($sx==1){
                		$where .= ' and jdc_wayuser.status>=0 and jdc_wayuser.status<=1';
                    // 已激活
                	}else if($sx==2){
                		$where .= ' and jdc_wayuser.status=2';
                    // 已关闭
                	}else if($sx==3){
                		$where .= ' and jdc_wayuser.status=3';
                	}
                }
                if($group){
                    // A组
                	if($group_param==1){
                		$where .= ' and jdc_wayuser.type=1';
                    //B组
                	}else if($group_param==2){
                		$where .= ' and jdc_wayuser.type=2';
                	}
                }
                $auth = ['-1'=>'-1','0'=>'1-0','1'=>'1-1','2'=>'1-2','3'=>'1-3','-2'=>'-2'];
                break;
            // 城市经理
            case '3':
                $adminids = M('admin')->where('pid='.$admin_data['id'])->field('id')->select();
                if($adminids){
                	$adminids = implode(',',array_column($adminids, 'id'));
                	$w_v = ' and jdc_wayuser.admin_id in('.$adminids.')';
                }else{
                	$w_v = ' and jdc_wayuser.admin_id in(0)';
                }
                $where = 'jdc_wayuser.status>=-2'.$w_v;
                if($wheresx){
                	if($sx==1){// 待审核
                		$where .= ' and jdc_wayuser.status<=1';
                	}else if($sx==2){// 已激活
                		$where = 'jdc_wayuser.status=2'.$w_v;
                	}else if($sx==3){// 已关闭
                		$where = 'jdc_wayuser.status=3'.$w_v;
                	}
                }
                if($group){
                	if($group_param==1){
                		$where .= ' and jdc_wayuser.type=1';
                	}else if($group_param==2){
                		$where .= ' and jdc_wayuser.type=2';
                	}
                }
                $auth = ['-1'=>'2--1','0'=>'2-0','1'=>'2-1','2'=>'2-2','3'=>'2-3','-2'=>'2-4'];
                break;
            // 省总
            case '4':
                $adminids = M('admin')->where('provinceid='.$admin_data['provinceid'])->field('id')->select();
                 if($adminids){
                 	$adminids = implode(',',array_column($adminids, 'id'));
                 	$w_v = ' and jdc_wayuser.admin_id in('.$adminids.')';
                 }else{
                 	$w_v = ' and jdc_wayuser.admin_id in(0)';
                 }
                $where = 'jdc_wayuser.status>=-2'.$w_v;
                if($wheresx){
                	if($sx==1){//待审核
                		$where .= ' and jdc_wayuser.status<=1';
                	}else if($sx==2){//已激活
                		$where = 'jdc_wayuser.status=2'.$w_v;
                	}else if($sx==3){//已关闭
                		$where .= ' and jdc_wayuser.status=3';
                	}
                }
                if($group){
                	if($group_param==1){
                		$where .= ' and jdc_wayuser.type=1';
                	}else if($group_param==2){
                		$where .= ' and jdc_wayuser.type=2';
                	}
                }
                $auth = ['-1'=>'3--1','0'=>'3-0','1'=>'3-1','2'=>'3-2','3'=>'3-3','-2'=>'2-4'];
                break;
            // 全国数据可见
             case '1100':
                $adminids = M('admin')->field('id')->select();
                if($adminids){
	             	$adminids = implode(',',array_column($adminids, 'id'));
	             	$w_v = ' and jdc_wayuser.admin_id in('.$adminids.')';
	            }else{
	             	$w_v = ' and jdc_wayuser.admin_id in(0)';
	            }
                $where = 'jdc_wayuser.status>=-2'.$w_v;
                if($wheresx){
                	if($sx==1){//待审核
                		$where .= ' and jdc_wayuser.status<=1';
                	}else if($sx==2){//已激活
                		$where = 'jdc_wayuser.status=2'.$w_v;
                	}else if($sx==3){//已关闭
                		$where .= ' and jdc_wayuser.status=3';
                	}
                }
                if($group){
                	if($group_param==1){
                		$where .= ' and jdc_wayuser.type=1';
                	}else if($group_param==2){
                		$where .= ' and jdc_wayuser.type=2';
                	}
                }
                $auth = ['-1'=>'3--1','0'=>'3-0','1'=>'3-1','2'=>'3-2','3'=>'3-3','-2'=>'2-4'];
                break;
            default:
                echo json_encode(['error'=>'2','message'=>'您没有权限查看！'],true);die;
                break;
        }
		$channel_data_arr = $channel_db->EchoAllChannel($field,$lr,$where,$auth,$arr_orderone[$order],$search);
		$weburl = C('WEBURL');
        $channel_data=$channel_data_arr['channel_data'];
        $pageData=$channel_data_arr['pageData'];
		if($channel_data){
			echo json_encode(['data'=>$channel_data,'page'=>$pageData,'auth'=>$admin_data['position'],'weburl'=>$weburl],true);
		}else{
			echo json_encode(['error'=>'1','message'=>'没有更多数据了！'],true);
		}
	}

	/**
	 * 风控审核操作
	 */
	public function ShenheFK() {
		$this->Islogin();
		$post = I('post.');
		$channel_mdb = M('wayuser');
        $wayusercode = M('wayuser_code');
		$admin_mdb = M('admin');
		$channel_db = D('channel');
		$meid = session('lampzuo_id');
		$admin_data = $admin_mdb->where('id='.$meid)->find();
        // 1 通过。2拒绝
		$status = $post['status'];
        // 1 通过。2拒绝
		$status_pd = ['1','2'];
		$status_dd = ['1'=>'2','2'=>'-1'];
        // 白名单列表（权限）
		$auth_position = ['5','501','502'];
		$wayid = $post['wayid'];
        // 账号权限是否为风控
		if(!in_array($admin_data['position'], $auth_position)){
			echo json_encode(['error'=>'1','message'=>'你没有权限操作！']);die;
		}
        // 是否存在占位数
		if(in_array($status,$status_pd)){
			$data['status'] = $status_dd[$status];
		}
		if(empty($post['remark'])){
			$post['remark'] = '未填写原因';
		}
		$channel_data = $channel_mdb->where('id='.$post['wayid'])->find();
		if($channel_data['status']!='1'){
			echo json_encode(['error'=>'1','message'=>'该操作暂未开放！请确认审核步骤！']);die;
		}
		if($status=='1'){
			$channel_data_af = $channel_mdb->field('waynum')->where('status>=2')->order('waynum desc')->find();
	    	if($channel_data_af){
	    		$newwaynum = $channel_data_af['waynum'] + 1;
	    	}else{
	    		$newwaynum = 20000;
	    	}
			$data['waynum'] = $newwaynum;
			$data['display'] = '1';
			$messageinfo = '已修改审核状态，并已生成二维码。';
		}else{
			$messageinfo = '已修改审核状态。';
		}
        // 操作时间
		$data['activation_time'] = time();
        // 操作人ID
		$data['auditorfk'] = $meid;
        // print_r($channel_data);die;
        // 重写渠道状态
		$channel_res = $channel_mdb->where('id='.$post['wayid'])->save($data);
		if($channel_res){
            $waycodeid = $channel_db->record($post['wayid'],$data['status'],$post['remark']);
            if($channel_data['scenetype'] == "1"){
                $qrcode = $this->QRcodeChannel($post['wayid']);
                if(!$qrcode){
                    echo json_encode(['error'=>'4','message'=>'二维码生成失败，请稍后重试。']);die;
                }
                $datacode = [
                    'code'=>0,
                    'aid'=>$channel_data['admin_id'],
                    'waynum'=>$newwaynum,
                    ];
            }else{
                $datacode = [
                    'code'=>$channel_data['code_number'],
                    'aid'=>$channel_data['admin_id'],
                    'waynum'=>$newwaynum,
                    ];
            }
            
                $wayusercode->add($datacode); 
			
			echo json_encode(['success'=>'OK','message'=>$messageinfo,'status'=>$status]);
		}else{
			echo json_encode(['error'=>'2','message'=>'修改失败！']);
		}
	}

	/**
	 * 城市经理审核操作
	 */
	public function ShenheCS() {
		$this->Islogin();
		$post = I('post.');
		$channel_mdb = M('wayuser');
		$admin_mdb = M('admin');
		$channel_db = D('channel');
		$meid = session('lampzuo_id');
		$admin_data = $admin_mdb->where('id='.$meid)->find();
        // 1 通过。2拒绝
		$status = $post['status'];
		$status_pd = ['1','2','3'];
		$status_dd = ['1'=>'1','2'=>'-1','3'=>'-2'];
		$wayid = $post['wayid'];
		if($admin_data['position']!='3'){
			echo json_encode(['error'=>'1','message'=>'你没有权限操作！']);die;
		}
		if(in_array($status,$status_pd)){
			$data['status'] = $status_dd[$status];
			$data['remark'] = $post["remark"];
		}
		$channel_data = $channel_mdb->where('id='.$post['wayid'])->find();
		
		if($channel_data['status']!='0'){
			echo json_encode(['error'=>'1','message'=>'该操作暂未开放！请确认审核步骤！']);die;
		}
        // 城市经理的操作人ID
		$data['auditorcs'] = $meid;
        // 城市经理的操作时间
		$data['citymanager_time'] = time();
        // 重写渠道状态
		$channel_res = $channel_mdb->where('id='.$post['wayid'])->save($data);
		if($channel_res&&$channel_db->record($post['wayid'],$data['status'],$post["remark"])){
			echo json_encode(['success'=>'OK','message'=>'修改成功！','status'=>$status]);
		}else{
			echo json_encode(['error'=>'2','message'=>'修改失败！']);
		}
	}

	/**
	 * 返回单条数据
	 */
	public function ChannelDetails() {
		$this->Islogin();
		$channel_db = D('Channel');
		$admin_mdb = M('admin');
		$id = I('post.id');

		$where = ['id'=>$id];
		$userid = session('lampzuo_id');
		$channel_data = $channel_db->OnefieldData($where);
		if(!$channel_data){
			echo json_encode(['error'=>'2','message'=>'没有找到相关数据！']);die;
		}
		// 成功的单数
		$channel_data['relationcount'] = $channel_db->OneRelationCount($id,'ztongguolu');
		if($channel_data['relationcount']>0){
			$relationcount = $channel_db->OneRelationCount($id,'danshu');
			$channel_data['allsuccessorderbf'] = $channel_data['relationcount']/$relationcount*100;
		}else{
			$channel_data['allsuccessorderbf'] = '暂无订单';
		}
        // 逾期的订单数
		$channel_data['ordertimeout'] = $channel_db->OneRelationCount($id,'yuqi');
        // 总金额
		$channel_data['allordermonye'] = $channel_db->OneRelationCount($id,'zongjine');
        // 分润金额
		$channel_data['groupmonye'] = $channel_db->OneRelationCount($id,'fenrun');
        // 被拒绝渠道
		$channel_data['orderrefuse'] = $channel_db->OneRelationCount($id,'beiju');
        // 当月订单总数
		$channel_data['monthorder'] = $channel_db->OneRelationCount($id,'yuetongguolu');
		if($channel_data['monthorder']>0){
            // 本月单数
			$monthorder = $channel_db->OneRelationCount($id,'benyue_danshu');
            // 计算成功率
			$channel_data['mothallsuccessorderbf'] = $channel_data['monthorder']/$monthorder*100;
		}else{
			$channel_data['mothallsuccessorderbf'] = '本月暂无订单';
		}
        // 本月被拒绝的渠道
		$channel_data['monthordertimeout'] = $channel_db->OneRelationCount($id,'benyue_beiju');
		$admin_data = $admin_mdb->where('id='.$channel_data['admin_id'])->field('usernum,position')->find();
		$meauth = $admin_mdb->where('id='.$userid)->field('position')->find()['position'];
        // 仅城市经理和省总可见下属顾问总数
		$auth = ['3','4'];
		if(in_array($meauth,$auth)){
			$channel_data['suoshu_gw'] = $admin_data['usernum'];
			if($meauth==$auth[1]){
				$channel_data['channelcity'] = $channel_db->OneRelationCount($channel_data['admin_id'],'suoshu_city');
			}
		}
        // 获取上次办单时间
		$channel_data['ordertimeend'] = $channel_db->OneRelationCount($id,'shangci_dan');
        // 获取驳回原因
		if($channel_data['status'] == -2){
			$wayuseropera = M('wayuser_operation');
			$res = $wayuseropera->where(array('wayuserid'=>$channel_data['id']))->order('id desc')->find();
			$channel_data['remarks'] = $res['remark'];
		}
		$channel_data['activation_time'] = date('Y-m-d H:i:s',$channel_data['activation_time']);
		$channel_data['create_time'] = date('Y-m-d H:i:s',$channel_data['create_time']);
		$channel_data['doorhead'] = serializeMysql($channel_data['doorhead'],1);
		$channel_data['receiptcode'] 	   = serializeMysql($channel_data['receiptcode'],1);
        $channel_data['roomscene']         = serializeMysql($channel_data['roomscene'],1);
        $channel_data['poster']            = serializeMysql($channel_data['poster'],1);
		$channel_data['otherdata_url'] 	   = serializeMysql($channel_data['otherdata_url'],1);
		echo json_encode(['success'=>'OK','data'=>$channel_data,'admin_position'=>$meauth['position'],'weburl'=>C('OSSURL').'/'],true);
		die;
	}

    /**
     * 修改渠道分组
     */
	public function EditType() {
		$this->Islogin();
		$channel_db = D('Channel');
		$id = I('post.id');
		$type = I('post.type');
		$cg = ['1','2'];
		$userid = session('lampzuo_id');
		if(!empty($type)){
			if(!in_array($type, $cg)){
				echo json_encode(['error'=>'1','message'=>'参数不正确！']);die;
			}
			$editdata['type'] = $type;
		}else{
			echo json_encode(['error'=>'1','message'=>'参数不正确！']);die;
		}
		$channel_data = $channel_db->OnefieldData(['id'=>$id]);
		$messageinfo = '修改成功！';
		$edit_res = $channel_db->EditChannelData(['id'=>$id],$editdata);
		if($edit_res) {
			echo json_encode(['success'=>'OK','message'=>$messageinfo]);die;
		}else{
			echo json_encode(['error'=>'2','message'=>'修改失败或分组无变化。']);die;
		}
	}

	/**
	 * 修改渠道状态
	 */
	public function EditActivation() {
		$this->Islogin();
		$channel_db = D('Channel');
		$user_db = D('admin');
		$id = I('post.id');
		$status = I('post.status');
         // 1激活  2关闭
		$cg = ['1','2'];
		$userid = session('lampzuo_id');
		if(!in_array($status, $cg)){
			echo json_encode(['error'=>'1','message'=>'参数不正确！']);die;
		}
		$channel_data = $channel_db->OnefieldData(['id'=>$id]);
		$me_user_data = $user_db->where('id='.$userid)->find();
		$auth = ['1','3'];
		if(!in_array($me_user_data['position'],$auth)){
			echo json_encode(['error'=>'3','message'=>'对不起，您的账号权限无法完成此操作！']);die;
		}

		if($channel_data['operationid']!='0'){
			if($channel_data['operationid']=='3'&&$me_user_data['position']=='1'){
				echo json_encode(['error'=>'3','message'=>'该渠道的激活人是城市经理人，您的账号权限无法完成此操作！']);die;
			}
		}
		$messageinfo = '修改成功！';
		if($status=='1'){
			$messageinfo = '激活成功！';
			$editdata['activation_time'] = time();
		}else{
			$messageinfo = '已关闭渠道！';
		}
		if($status=='1'&&empty($channel_data['qrcode_url'])){
			$qrcode = $this->QRcodeChannel($id);
			if(!$qrcode){
				echo json_encode(['error'=>'4','message'=>'二维码生成失败，请稍后重试。']);die;
			}
			$messageinfo = '激活成功，并已生成二维码。';
			$editdata['activation_time'] = time();
		}
		$status_qd = ['1'=>'2','2'=>'3'];
		$editdata['operationid'] = $me_user_data['position'];
		$editdata['status'] = $status_qd[$status];
		$edit_res = $channel_db->EditChannelData(['id'=>$id],$editdata);
		if($edit_res) {
			echo json_encode(['success'=>'OK','message'=>$messageinfo,'status'=>$status]);die;
		}else{
			echo json_encode(['error'=>'2','message'=>'修改失败或数据无变化。']);die;
		}
	}

	/**
	 * 渠道生成二维码
	 */
	private function QRcodeChannel($id) {
        $channel_db = D('Channel');
		$user_db = M('Admin');
		$channel_data = $channel_db->OnefieldData(['id'=>$id]);
        $me_user_data = $user_db->where('id = '.$channel_data['admin_id'])->find();
		$date = date('Y-m-d');
		$path = './Public/Uploads/qrcode/'.$date.'/';
		if(!is_dir($path)){
			mkdir($path,0777,true);
		}
        //随机一个文件名
		do{
			$filename = time().rand(1000,9999).".png";
        //判断是否存在
		}while(file_exists($path.$filename));
		$weburl = C('WEBURL');
		$qrres = scerweima($weburl.'PIGjdc/login_first_step.html?pid='.$channel_data['admin_id'].'&waynum='.$channel_data['waynum'],$path.$filename,$me_user_data['usernum']);
        // $qrres = $this->ceshiscerweima($weburl.'PIGjdc/login_first_step.html?pid='.$userid.'&code='.$chennlnum,$path.$chennode,$usernum,$chennlnum);
		if(!$qrres){
			return false;
		}
		$newfile = $date.'/'.$filename;
        // 修改渠道的二维码地址
        $create_qrcode = $channel_db->EditChannelData(['id'=>$id],['qrcode_url'=>$newfile]);
        //ossPutObject($datepath.'/'.$filename,file_get_contents(C('PUBLIC_ROUTE').substr($path.$filename,1)));
        if($create_qrcode){
        	return $newfile;
        }else{
        	return false;
        }
	}

    /**
     * 统计各渠道对应的用户数量
     * 生成的Excel文件将存放在 Public/Uploads/ChannelCount 下，并以当天日期命名
     */
    public function CountChannelUser() 
    {
        $meid = $this->Islogin();
        // $meid = 7;
        $admin_mdb =  M('admin');
        $wayuser_mdb =  M('wayuser');
        $user_mdb =  M('user');
        $city_db = D('city');
        $medata = $admin_mdb->where('id='.$meid)->find();
        switch ($medata['position']) {
            // 全国权限账号
            case '1100':
                $where_city = '';
                if(!empty(I('get.province'))){
                    $where_city = ' and provinceid='.I('get.province');
                }
                $response['provinceid'] = $city_db->CityGetAll(false,false,false);
                $iscs = false;
                $response['position'] = 1100;
                break;
            // 省总权限
            case '4':
                $where_city = ' and provinceid='.$medata['provinceid'];
                $iscs = false;
                $response['position'] = 4;
                break;
            // 城市经理
            case '3':
                $where_city = ' and pid='.$medata['id'];
                $iscs = true;
                $response['position'] = 3;
                break;
            default:
                exit(json_encode(['error'=>'1','message'=>'您的账号权限不涉及本功能！']));
        }
        $BeginDate = strtotime(date("Y-m-01"));
        $EndDate = mktime(0, 0, 0,date('m')+1,1)-1;
        $Beginday = strtotime(date('Y-m-01 00:00:00'));
        $EndDay = strtotime(date('Y-m-15 23:59:59'));
        // $timesql = ' and create_time>='.$BeginDate.' and create_time<='.$EndDate;
        $timesql = '';
        $time_reg_sql =  ' and create_time>='.$Beginday.' and create_time<='.$EndDay;
        // 所有城市经理
        $manager = $admin_mdb->where('position=3'.$where_city.$this->istest['testsql'])->select();
        $channelcount = [];
        // 城市经理总数
        $cscount = count($manager);
        $gwcount = 0;
        $data = [];
        // 渠道状态
        $status_arr = ['0'=>'等待城市经理审核','1'=>'等待风控审核','2'=>'已激活','3'=>'关闭状态（已通过审核）','-1'=>'被拒绝','-2'=>'被驳回（正在修改）'];
        for ($i=0; $i <  $cscount; $i++) { 
            // 城市经理下属的所有GW
            $Gwdata = $admin_mdb->where('pid='.$manager[$i]['id'].' and position=1'.$this->istest['testsql'])->field('id,name,tel')->select();
            $manager_sheet_title[] = $manager[$i]['name'];
            $data[$i] = [];
            $manager_regt = 0;
            $manager_regt_day = 0;
            // 统计渠道数据
            if(!$Gwdata){
                $manager[$i]['channelcount'] = 0;
                $manager[$i]['channel_create_count'] = 0;
                $manager[$i]['channel_success_count'] = 0;
                $manager[$i]['channel_refuse_count'] = 0;
                $manager[$i]['channel_back_count'] = 0;
                $manager[$i]['GWcount'] = 0;
                $manager[$i]['GWlist'] = [];
            }else{
                $manager[$i]['GWcount'] = count($Gwdata);
                $Gwdataids = implode(',',array_column($Gwdata,'id'));
                $manager[$i]['channelcount'] = $wayuser_mdb->where('admin_id in('.$Gwdataids.')'.$timesql)->count();
                $data[$i][] = ['顾问姓名','','','','',''];
                for ($s=0; $s < count($Gwdata); $s++) { 
                    $Gwdata[$s]['channel_count'] = $wayuser_mdb->where('admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    $manager[$i]['channel_create_count'] += $Gwdata[$s]['channel_create_count'] = $wayuser_mdb->where('status>=0 and status<=1 and admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    $manager[$i]['channel_success_count'] += $Gwdata[$s]['channel_success_count'] = $wayuser_mdb->where('status=2 and admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    $manager[$i]['channel_refuse_count'] += $Gwdata[$s]['channel_refuse_count'] = $wayuser_mdb->where('status=-1 and admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    $manager[$i]['channel_back_count'] += $Gwdata[$s]['channel_back_count'] = $wayuser_mdb->where('status=-2 and admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    $gw_regt = 0;
                    $gw_regt_day = 0;
                    $waydata = $wayuser_mdb->where('admin_id='.$Gwdata[$s]['id'].$timesql)->select();

                    for ($j=0; $j < $Gwdata[$s]['channel_count']; $j++) { 
                        $channel_regt = $user_mdb->where('waynum='.$waydata[$j]['waynum'].' and waynum<>0')->count();
                        $gw_regt += $channel_regt;
                        $channel_regt_day = $user_mdb->where('waynum='.$waydata[$j]['waynum'].' and waynum<>0'.$time_reg_sql)->count();
                        $gw_regt_day += $channel_regt_day;
                    }
                    $manager_regt_day += $gw_regt_day;
                    $data[$i][] = [$Gwdata[$s]['name'], '姓名', '手机号', '推荐码', '状态', '注册用户总数', '3月1日-3月15日增长用户数'];
                    $data[$i][] = ['按顾问“'.$Gwdata[$s]['name'].'”统计', '注册用户总数：'.$gw_regt, '3月1日-3月15日增长用户数：'.$gw_regt_day, '', '', '', ];
                    $data[$i][] = ['','','','','',''];

                    for ($j=0; $j < $Gwdata[$s]['channel_count']; $j++) { 
                        $manager_regt += $channel_regt = $user_mdb->where('waynum='.$waydata[$j]['waynum'].' and waynum<>0')->count();
                        $channel_regt_day = $user_mdb->where('waynum='.$waydata[$j]['waynum'].' and waynum<>0'.$time_reg_sql)->count();
                        $data[$i][] = [
                            $Gwdata[$s]['name'],
                            $waydata[$j]['name'],
                            $waydata[$j]['tel'],
                            $waydata[$j]['waynum'],
                            $status_arr[$waydata[$j]['status']],
                            $channel_regt,
                            $channel_regt_day,
                        ];
                    }
                    
                    
                }
            }
            $manager_title[$i] = ['按城市经理统计',
              '注册用户数：'.$manager_regt,
              '3月1日-3月15日增长用户数：'.$manager_regt_day,
              '',
              '',
              ''
            ];
        }
        $filename_n = '统计本月各渠道用户总数（截止'.date('Y-m-15').'）';
        // 生成Excel并返回文件名称
        $filename = ExportExcelTable($manager_title,$data,$manager_sheet_title,$filename_n,'./Public/Uploads/ChannelCount/',true);
        exit(json_encode(['success'=>'OK','filename'=>$filename_n,'message'=>$filename_n.'导出成功！']));
    }

   

    /**
     * 导出Excel
     */
    public function createChannelExcel()
    {
        $meid = $this->Islogin();
        // $meid = "7";
        $admin_mdb =  M('admin');
        $wayuser_mdb =  M('wayuser');
        $city_db = D('city');
        $medata = $admin_mdb->where('id='.$meid)->find();
        switch ($medata['position']) {
            // 全国权限
            case '1100':
                $where_city = '';
                if(!empty(I('get.province'))){
                    $where_city = ' and provinceid='.I('get.province');
                }
                $iscs = false;
                // $where_city = ' and provinceid=1';
                // 获取城市列表供选择
                $response['provinceid'] = $city_db->CityGetAll(false,false,false);
                $response['position'] = 1100;
                break;
            // 省总权限
            case '4':
                $where_city = ' and provinceid='.$medata['provinceid'];
                $iscs = false;
                $response['position'] = 4;
                break;
            // 城市经理
            case '3':
                $where_city = ' and pid='.$medata['id'];
                $iscs = true;
                $response['position'] = 3;
                break;
            default:
                exit(json_encode(['error'=>'1','message'=>'您的账号权限不涉及本功能！']));
        }
        $BeginDate = strtotime(date("Y-m-01"));
        $EndDate = mktime(0, 0, 0,date('m')+1,1)-1;
        $Beginday = strtotime(date('Y-m-d 00:00:00'));
        $EndDay = strtotime(date('Y-m-d 23:59:59'));
        // $timesql = ' and create_time>='.$Beginday.' and create_time<='.$EndDay;
        $timesql = '';
        // 所有城市经理
        $manager = $admin_mdb->where('position=3'.$where_city.$this->istest['testsql'])->select();
        $channelcount = [];
        // 城市经理总数
        $cscount = count($manager);
        $gwcount = 0;
        $data = [];
        // 渠道状态
        $status_arr = ['0'=>'等待城市经理审核','1'=>'等待风控审核','2'=>'已激活','3'=>'关闭状态（已通过审核）','-1'=>'被拒绝','-2'=>'被驳回（正在修改）'];
        for ($i=0; $i <  $cscount; $i++) { 
            // 城市经理下属的所有GW
            $Gwdata = $admin_mdb->where('pid='.$manager[$i]['id'].' and position=1'.$this->istest['testsql'])->field('id,name,tel')->select();
            $manager_sheet_title[] = $manager[$i]['name'];
            $data[$i] = [];
            // 统计渠道数据
            if(!$Gwdata){
                $manager[$i]['channelcount'] = 0;
                $manager[$i]['channel_create_count'] = 0;
                $manager[$i]['channel_success_count'] = 0;
                $manager[$i]['channel_refuse_count'] = 0;
                $manager[$i]['channel_back_count'] = 0;
                $manager[$i]['GWcount'] = 0;
                $manager[$i]['GWlist'] = [];
            }else{
                $manager[$i]['GWcount'] = count($Gwdata);
                $Gwdataids = implode(',',array_column($Gwdata,'id'));
                $manager[$i]['channelcount'] = $wayuser_mdb->where('admin_id in('.$Gwdataids.')'.$timesql)->count();
                $data[$i][] = ['顾问姓名','','','','',''];
                for ($s=0; $s < count($Gwdata); $s++) { 
                    // 总数
                    $Gwdata[$s]['channel_count'] = $wayuser_mdb->where('admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    // 待审
                    $manager[$i]['channel_create_count'] += $Gwdata[$s]['channel_create_count'] = $wayuser_mdb->where('status>=0 and status<=1 and admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    // 通过
                    $manager[$i]['channel_success_count'] += $Gwdata[$s]['channel_success_count'] = $wayuser_mdb->where('status=2 and admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    // 被拒
                    $manager[$i]['channel_refuse_count'] += $Gwdata[$s]['channel_refuse_count'] = $wayuser_mdb->where('status=-1 and admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    // 被驳回
                    $manager[$i]['channel_back_count'] += $Gwdata[$s]['channel_back_count'] = $wayuser_mdb->where('status=-2 and admin_id='.$Gwdata[$s]['id'].$timesql)->count();
                    $data[$i][] = ['','','','','',''];
                    // 表头（顾问单位）
                    $data[$i][] = [
                        $Gwdata[$s]['name'],
                        '姓名',
                        '手机号',
                        '工作单位',
                        '推荐码',
                        '状态'
                    ];
                    $data[$i][] = [
                        '按顾问“'.$Gwdata[$s]['name'].'”统计',
                        '渠道总数：'.$Gwdata[$s]['channel_count'],
                        '审核中渠道：'.$Gwdata[$s]['channel_create_count'],
                        '已通过渠道：'.$Gwdata[$s]['channel_success_count'],
                        '被拒绝渠道：'.$Gwdata[$s]['channel_refuse_count'],
                        '被驳回渠道：'.$Gwdata[$s]['channel_back_count']
                    ];
                    $waydata = $wayuser_mdb->where('admin_id='.$Gwdata[$s]['id'].$timesql)->select();
                    for ($j=0; $j < $Gwdata[$s]['channel_count']; $j++) { 
                        $data[$i][] = [
                            $Gwdata[$s]['name'],
                            $waydata[$j]['name'],
                            $waydata[$j]['tel'],
                            $waydata[$j]['company'],
                            $waydata[$j]['waynum'],
                            $status_arr[$waydata[$j]['status']]
                        ];
                    }
                }
            }
            // 表头（城市经理单位）
            $manager_title[$i] = ['按城市经理统计',
              '渠道总数：'.$manager[$i]['channelcount'],
              '审核中渠道：'.$manager[$i]['channel_create_count'],
              '已通过渠道：'.$manager[$i]['channel_success_count'],
              '被拒绝渠道：'.$manager[$i]['channel_refuse_count'],
              '被驳回渠道：'.$manager[$i]['channel_back_count']
            ];
        }
        $filename_n = '截止'.date('Y-m-d').'渠道数据';
        // 生成Excel并返回文件名称
        $filename = ExportExcelTable($manager_title,$data,$manager_sheet_title,$filename_n,'./Public/Uploads/ChannelCount/');
        exit(json_encode(['success'=>'OK','filename'=>$filename_n,'message'=>$filename_n.'导出成功！']));
    }
    /**
     * 下载excel
     * @return [type] [description]
     */
    public function exportExcel() {
        $filename_str = I('get.filename');
        if(empty($filename_str)){
           return false;
        }
        $path = C('PUBLIC_ROUTE').'/Public/Uploads/ChannelCount/';
        $filename = $path.ltrim($filename_str,'/').'.xlsx';
        header("Content-type: octet/stream");
        header("Content-Disposition:attachment;filename=$filename_str.xlsx");  
        // 下载文件大小
        header('Content-Length:'.filesize($filename));
        // 读取文件内容
        readfile($filename);
    }

	/**
	 * 图片处理
	 * @param  [type] $data [description]
	 * @return [type]       [description]
	 */
	public function isFuncgetImgesQudao($data){
        // print_r($data);die;
        //收款码
		$receiptcode  = array();
        //门头照片
		$doorhead     = array();
        //实景照片
        $roomscene    = array();
        //海报照片
        $poster       = array();
        //其他
		$qita         = array();
		$config = C('DOWNLOAD_UPLOAD');
		$config['rootPath'] =  './Public/Uploads/';
		if(!is_dir($config['rootPath'])){
            chmod($config['rootPath'],0777);
        }
		if($data['receiptcode']){
			$config['subName']  = "receiptcode";
            $datepath = 'Public/Uploads/receiptcode';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
			$upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['receiptcode']['name'] as $key=>$value){
                $file1=array();
                $file1["receiptcode"]['name']=$value;
                $file1["receiptcode"]['type']=$data['receiptcode']["type"][$key];
                $file1["receiptcode"]['tmp_name']=$data['receiptcode']["tmp_name"][$key];
                $file1["receiptcode"]['error']=$data['receiptcode']["error"][$key];
                $file1["receiptcode"]['size']=$data['receiptcode']["size"][$key];
                $info   =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['receiptcode']['savepath'].$info['receiptcode']['savename']);
                array_push($receiptcode,$config['rootPath'].$info['receiptcode']['savepath'].$info['receiptcode']['savename']);
            }
		}
        if($data['doorhead']){
            $config['subName']  = "identifyprove_url";
            $datepath = 'Public/Uploads/identifyprove_url';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
            $upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['doorhead']['name'] as $key=>$value){
                $type     = $value;//文件名
                $type1    = getImagetype($type);
                if(!$type1){
                    echo json_encode(['error'=>'ERROR','message'=>'其他资料请上传图片格式！']);die;
                }
                $file1=array();
                $file1["doorhead"]['name']=$value;
                $file1["doorhead"]['type']=$data['doorhead']["type"][$key];
                $file1["doorhead"]['tmp_name']=$data['doorhead']["tmp_name"][$key];
                $file1["doorhead"]['error']=$data['doorhead']["error"][$key];
                $file1["doorhead"]['size']=$data['doorhead']["size"][$key];
                $info   =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['doorhead']['savepath'].$info['doorhead']['savename']);
                array_push($doorhead,$config['rootPath'].$info['doorhead']['savepath'].$info['doorhead']['savename']);
            }
        }
		
		if($data['roomscene']){
            $config['subName']  = "otherdata_url";
            $datepath = 'Public/Uploads/otherdata_url';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
            $upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['roomscene']['name'] as $key=>$value){
                $type     = $value;//文件名
                $type1    = getImagetype($type);
                if(!$type1){
                    echo json_encode(['error'=>'ERROR','message'=>'其他资料请上传图片格式！']);die;
                }
                $file1=array();
                $file1["roomscene"]['name']=$value;
                $file1["roomscene"]['type']=$data['roomscene']["type"][$key];
                $file1["roomscene"]['tmp_name']=$data['roomscene']["tmp_name"][$key];
                $file1["roomscene"]['error']=$data['roomscene']["error"][$key];
                $file1["roomscene"]['size']=$data['roomscene']["size"][$key];
                $info   =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['roomscene']['savepath'].$info['roomscene']['savename']);
                array_push($roomscene,$config['rootPath'].$info['roomscene']['savepath'].$info['roomscene']['savename']);
            }
        }
        if($data['poster']){
            $config['subName']  = "poster";
            $datepath = 'Public/Uploads/poster';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
            $upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['poster']['name'] as $key=>$value){
                $type     = $value;//文件名
                $type1    = getImagetype($type);
                if(!$type1){
                    echo json_encode(['error'=>'3','message'=>'授权证明请上传图片格式！']);die;
                }
                $file1=array();
                $file1["poster"]['name']=$value;
                $file1["poster"]['type']=$data['poster']["type"][$key];
                $file1["poster"]['tmp_name']=$data['poster']["tmp_name"][$key];
                $file1["poster"]['error']=$data['poster']["error"][$key];
                $file1["poster"]['size']=$data['poster']["size"][$key];
                $info   =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['poster']['savepath'].$info['poster']['savename']);
                array_push($poster,$config['rootPath'].$info['poster']['savepath'].$info['poster']['savename']);
            }
        }
        if($data['qita']){
			$config['subName']  = "otherdata_url";
            $datepath = 'Public/Uploads/otherdata_url';
            if(!ossGetObject($datepath))
            {
                //检查是否有该文件夹，如果没有就创建，并给予最高权限
                $res=createObjectDir($datepath);
            }
			$upload = new \Think\Upload($config);
            $info=array();
            foreach ($data['qita']['name'] as $key=>$value){
                $type     = $value;//文件名
                $type1    = getImagetype($type);
                if(!$type1){
                    echo json_encode(['error'=>'ERROR','message'=>'其他资料请上传图片格式！']);die;
                }
                $file1=array();
                $file1["qita"]['name']=$value;
                $file1["qita"]['type']=$data['qita']["type"][$key];
                $file1["qita"]['tmp_name']=$data['qita']["tmp_name"][$key];
                $file1["qita"]['error']=$data['qita']["error"][$key];
                $file1["qita"]['size']=$data['qita']["size"][$key];
                $info   =   $upload->upload($file1);
                ImgThumb($config['rootPath'].$info['qita']['savepath'].$info['qita']['savename']);
                array_push($qita,$config['rootPath'].$info['qita']['savepath'].$info['qita']['savename']);
            }
		}
        
        foreach ($receiptcode as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
        foreach ($doorhead as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
        foreach ($qita as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
        foreach ($roomscene as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
        foreach ($poster as $key => $value) {
            $res = substr($value,1);
            ossPutObject(ltrim($res,'/'),file_get_contents($value));
            @unlink($value);
        }
		$addarr= array(
                "receiptcode"   => $receiptcode,
                "doorhead"      => $doorhead,
                "qita"          => $qita,
                "roomscene"     => $roomscene,
                "poster"        => $poster,
              );
		return $addarr;
	}
}

